package br.com.ufpr.sgp.pages;

import javax.ejb.EJB;

import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.head.JavaScriptHeaderItem;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.CheckBox;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.markup.html.form.StatelessForm;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.request.RequestHandlerStack.ReplaceHandlerException;
import org.apache.wicket.request.cycle.RequestCycle;
import org.wicketstuff.annotation.mount.MountPath;

import br.com.sebrae.pr.sgp.entities.Usuario;
import br.com.sebrae.pr.sgp.services.UsuarioServiceRemote;
import br.com.sebrae.pr.sgp.util.MD5;
import br.com.sebrae.pr.sgp.util.exceptions.ExcecaoDeApresentacao;
import br.com.sebrae.pr.sgp.util.exceptions.ExcecaoDeNegocio;
import br.com.sebrae.pr.sgp.util.exceptions.TipoErro;
import br.com.sebrae.pr.sgp.util.exceptions.TratadorDeExcecoes;
import br.com.ufpr.sgp.WicketApplication;
import br.com.ufpr.sgp.util.cookies.CookieService;
import br.com.ufpr.sgp.util.session.CustomSession;
import br.com.ufpr.sgp.util.session.CustomSessionProvider;
import br.com.ufpr.util.base.BasePage;

@MountPath("Login")
public class LoginPage extends BasePage {
    private static final long serialVersionUID = -5426958666882455336L;

    public LoginPage() {
        add(new LoginForm("loginForm", LoginPage.this));
    }

    static class LoginForm extends StatelessForm<LoginPage> {
        private static final long serialVersionUID = -2832873183098470774L;

        @EJB(name = "UsuarioServiceImpl")
        private UsuarioServiceRemote usuarioServiceRemote;

        private String nmeLogin;
        private String desSenha;
        private boolean rememberMe;

        public LoginForm(final String id, final LoginPage loginPage) {
            super(id);
            
            add(new RequiredTextField<String>("nmeLogin", new PropertyModel<String>(LoginForm.this, "nmeLogin")).setRequired(true)
                    .setLabel(new ResourceModel("Login")));
            add(new PasswordTextField("desSenha", new PropertyModel<String>(LoginForm.this, "desSenha")).setRequired(true).setLabel(
                    new ResourceModel("Senha")));
            add(new CheckBox("rememberMe", new PropertyModel<Boolean>(LoginForm.this, "rememberMe")));

            add(new BookmarkablePageLink<EsqueciMinhaSenhaPage>("lnkEsqueciSenha", EsqueciMinhaSenhaPage.class));

            add(new Button("btnLogin") {
                private static final long serialVersionUID = -368229077535401186L;

                public void onSubmit() {
                    try {
                        final Usuario usu = usuarioServiceRemote.pesquisarPorLoginSenha(nmeLogin, MD5.encode(desSenha));
                        if (usu != null && usu.getId() > 0) {
                            CustomSession.get().setUsuario(usu);

                            if (rememberMe) {
                                final CookieService cookieService = WicketApplication.get().getCookieService();
                                cookieService.saveCookie(getResponse(), CustomSessionProvider.REMEMBER_ME_LOGIN_COOKIE, nmeLogin,
                                        CustomSessionProvider.REMEMBER_ME_DURATION_IN_DAYS);
                                cookieService.saveCookie(getResponse(), CustomSessionProvider.REMEMBER_ME_PASSWORD_COOKIE,
                                        MD5.encode(desSenha), CustomSessionProvider.REMEMBER_ME_DURATION_IN_DAYS);
                            } else {
                            	WicketApplication
                                        .get()
                                        .getCookieService()
                                        .removeCookieIfPresent(RequestCycle.get().getRequest(), RequestCycle.get().getResponse(),
                                                CustomSessionProvider.REMEMBER_ME_LOGIN_COOKIE);
                            	WicketApplication
                                        .get()
                                        .getCookieService()
                                        .removeCookieIfPresent(RequestCycle.get().getRequest(), RequestCycle.get().getResponse(),
                                                CustomSessionProvider.REMEMBER_ME_PASSWORD_COOKIE);
                            }

                            continueToOriginalDestination();
                            setResponsePage(WicketApplication.get().getHomePage());
                        } else {
                            throw new ExcecaoDeNegocio("app.login.usuarioOuSenhaIncorreto");
                        }
                    } catch (ReplaceHandlerException e) {
                        throw e;

                    } catch (Exception e) {

                        final ExcecaoDeApresentacao ea = TratadorDeExcecoes.convertException(e);
                        loginPage.adicionaMensagem(ea.getTipoErro() != null ? ea.getTipoErro() : TipoErro.ERRO, ea.getMensagem());
                        loginPage.atualizarFeedbackPanel();

                    }
                }
            });

        }

    }

    @Override
    public void renderHead(IHeaderResponse response) {
        super.renderHead(response);
        response.render(JavaScriptHeaderItem.forReference(getApplication().getJavaScriptLibrarySettings().getJQueryReference()));
    }
}

